<template>
  <div class="app-container">
    <div class="nav">
      <router-link to="/dashboard/dash" class="nav-link"><span>首页</span></router-link>
      <router-link 
        :to="{ 
          name: 'project-manage', 
          params: { 
            param: staId,
            standardName: standardName 
          }
        }" 
        class="nav-link"
      >
        <span>/</span><span>{{ standardName }}</span>
      </router-link>
      <router-link 
        :to="{
          name: 'project-manage',
          params: {
            param: staId,
            standardName: standardName,
            staName: standardName
          }
        }"
        class="nav-link"
      >
        <span>/</span><span>{{ projectName }}</span>
      </router-link>
      <router-link 
        :to="{
          name: 'moudle_select',
          params: {
            param: projectId,
            projectName: projectName,
            standardName: standardName,
            staId: staId
          }
        }"
        class="nav-link"
      >
        <span>/</span><span>模块选择</span>
      </router-link>
      <router-link 
        :to="{
          name: 'equip_manage',
          params: {
            param: projectId,
            projectName: projectName,
            standardName: standardName,
            staId: staId
          }
        }"
        class="nav-link"
      >
        <span>/</span><span>设备管理</span>
      </router-link>
      <router-link 
        :to="{
          name: 'equip_plan',
          params: {
            id: equipId,
            param: projectId,
            projectName: projectName,
            standardName: standardName,
            staId: staId
          }
        }"
        class="nav-link"
      >
        <span>/</span><span>设备方案</span>
      </router-link>
      <span>/</span><span class="current-page">添加方案</span>
      <div class="nav-back">
        <el-button type="text" @click="handleBack">
          <i class="el-icon-arrow-left"></i> 返回
        </el-button>
      </div>
    </div>

    <!-- 添加方案表单 -->
    <div class="add-equip-container">
      <div class="form-container">
        <el-form 
          ref="form" 
          :model="form" 
          :rules="rules" 
          label-width="100px"
        >
          <el-form-item label="方案名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入方案名称"></el-input>
          </el-form-item>

          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="form.manufacturer" placeholder="请输入生产厂家"></el-input>
          </el-form-item>

          <el-form-item label="仪器照片" prop="image">
            <div class="upload-container">
            <el-upload
              class="image-uploader"
              :action="'http://localhost:8081/uploadPicture111'"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeImageUpload"
              :headers="headers">
              <img 
                v-if="form.image" 
                :src="getImageSrc(form.image)" 
                class="uploaded-image"
                @error="handleImageError"
              >
              <i v-else class="el-icon-plus upload-icon"></i>
            </el-upload>
            <div class="upload-tip">支持 jpg、png 格式大小不超过 5MB</div>
           </div>
          </el-form-item>

          <el-form-item label="详情文件" prop="details">
          <div class="pdf-upload-container">
            <el-upload
              class="pdf-uploader"
              :action="'http://localhost:8081/uploadPDF'"
              :show-file-list="true"
              :on-success="handlePdfSuccess"
              :on-error="handleUploadError"
              :before-upload="beforePdfUpload"
              :headers="headers"
              :limit="1"
              accept=".pdf">
              <el-button type="primary">
                <i class="el-icon-upload"></i> 上传PDF文件
              </el-button>
              <div class="upload-tip">请上传PDF格式文件，大小不超过10MB</div>
            </el-upload>
          </div>
        </el-form-item>

          <el-form-item class="form-buttons">
            <el-button @click="handleBack">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "AddEquip",
  data() {
    return {
      baseUrl: 'http://localhost:8081',
      form: {
        name: "",
        image: "",
        manufacturer: "",
        details: "",
      },
      rules: {
        name: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
        manufacturer: [
          { required: true, message: "请输入生产厂家", trigger: "blur" },
        ],
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      imageFile: null,
      pdfFile: null,
      projectId: null,
      staId: null,
      standardName: '',
      projectName: '',
      equipId: null,
      flaggg:null,

      soId:null,

      eid:null,

      headers: {
        Authorization: 'Bearer ' + this.$store.state.user.token
      },
      imageUrl: ''

    };
  },
  async created() {
    const { equipId, param, projectName, standardName, staId } = this.$route.params;
    
    this.equipId = equipId || localStorage.getItem('equipId');
    this.projectId = param || localStorage.getItem('projectId');
    this.projectName = projectName || localStorage.getItem('projectName') || '未知项目';
    this.standardName = standardName || localStorage.getItem('standardName') || '未知标准';
    this.staId = staId || localStorage.getItem('staId');
    
    // 存储当前值
    if (equipId) localStorage.setItem('equipId', equipId);
    if (param) localStorage.setItem('projectId', param);
    if (projectName) localStorage.setItem('projectName', projectName);
    if (standardName) localStorage.setItem('standardName', standardName);
    if (staId) localStorage.setItem('staId', staId);

    if (this.$route.params.flag) {
    this.flaggg = this.$route.params.flag;//1代表添加，2代表编辑

    if(this.flaggg==1){
      this.eid = this.$route.params.eid;
      // 保存到 localStorage
      localStorage.setItem('currentEquId', this.eid);
    }

    if(this.flaggg==2){
      this.soId = this.$route.params.id;
      // 保存到 localStorage
      localStorage.setItem('currentSolutionId', this.soId);
    }

  } else {
    this.eid = localStorage.getItem('currentEquId');
    // 如果路由参数丢失，从 localStorage 获取
    this.soId = localStorage.getItem('currentSolutionId');

    if(!this.eid){
      console.error("未接收到 eid 参数");
      this.$message.error("设备ID获取失败");
      return;
    }
    if (!this.soId) {
      console.error("未接收到 soId 参数");
      this.$message.error("方案ID获取失败");
      return;
    }
  }
  },
  methods: {
    getImageSrc(imageName) {
      if (!imageName) return '';
      // 使用完整的URL路径
      return `${this.baseUrl}/src/assets/soluimages/${imageName}`;
    },
    handleImageSuccess(response) {
      this.form.image = response.data;
      console.log('上传后的图片地址:', this.getImageSrc(response.data));
      this.$message.success('图片上传成功');
    },
    handleUploadError(err) {
      this.$message.error("图片上传失败：" + err.message);
    },
    beforeImageUpload(file) {
      const isValidFormat = ["image/jpeg", "image/png"].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isValidFormat) {
        this.$message.error("图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("图片大小不能超过 5MB!");
        return false;
      }
      return true;
    },
    handlePdfSuccess(response) {
      this.form.details = response.data
      console.log('上传后的PDF地址:', this.form.details);
      this.$message.success('PDF文件上传成功')
    },
    beforePdfUpload(file) {
      const isPdf = file.type === "application/pdf";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isPdf) {
        this.$message.error("只能上传PDF文件!");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("文件大小不能超过 10MB!");
        return false;
      }
      return true;
    },
    handlePdfFileChange(event) {
      this.pdfFile = event.target.files[0];
    },
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            if(this.flaggg==2) {
              const formData = {
                soId : this.soId,
                soName : this.form.name,
                factory : this.form.manufacturer,
                soUrl : this.form.details,
                picture : this.form.image,
              };

              const response = await axios.post('/modifySolution', formData);
              if (response.status === 200) {
                this.$message.success('编辑成功');
                this.goBack();
              } else {
                this.$message.error('编辑失败');
              }
            }
            else if(this.flaggg==1) {
              const formData = {
                eId: parseInt(this.eid),
                soName: this.form.name,
                factory: this.form.manufacturer,
                soUrl: this.form.details,
                picture: this.form.image
              };

              console.log('准备提交的数据:', formData);

              const response = await axios.put('/addSolution', formData, {
                headers: {
                  'Content-Type': 'application/json'
                }
              });

              if (response.status === 200) {
                this.$message.success('添加成功');
                this.goBack();
              } else {
                this.$message.error('添加失败');
              }
            }
          } catch (error) {
            console.error('提交失败:', error);
            console.error('错误响应:', error.response);
            this.$message.error(`添加失败：${error.response?.data?.message || error.message}`);
          }
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    handleImageError(e) {
      console.error('图片加载失败');
      this.$message.error('图片加载失败');
      this.imageUrl = '';
    },
    handleImageUpload(event) {
      this.imageFile = event.target.files[0];
    },
    handlePdfFileChange(event) {
      this.pdfFile = event.target.files[0];
    },
    triggerImageInput() {
      this.$refs.imageInput.click();
    },
    triggerPdfInput() {
      this.$refs.pdfInput.click();
    },
    removeImage() {
      this.form.image = "";
      this.imageFile = null;
      this.$refs.imageInput.value = "";
    },
    removePdf() {
      this.form.details = "";
      this.pdfFile = null;
      this.$refs.pdfInput.value = "";
    },
    handleBack() {
      this.$router.push({
        name: 'equip_plan',
        params: {
          id: this.equipId,
          param: this.projectId,
          projectName: this.projectName,
          standardName: this.standardName,
          staId: this.staId
        },
        replace: true
      });
    },
    // 加载方案详情的方法
    async loadSolutionDetails(id) {
      try {
        const response = await this.$http.get(`/getSolutionDetails/${id}`);
        if (response.data) {
          this.form = {
            name: response.data.name,
            image: response.data.image,
            manufacturer: response.data.manufacturer,
            details: response.data.details
          };
        }
      } catch (error) {
        console.error('加载方案详情失败:', error);
        this.$message.error('加载方案详情失败');
      }
    }
  },
};
</script>

<style scoped>
.add-equip-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.form-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  text-align: center;
}

.form-buttons {
  margin-top: 30px;
  text-align: center;
}

:deep(.el-form-item__content) {
  display: flex;
  justify-content: center;
}

:deep(.el-upload) {
  width: 100%;
  text-align: center;
}

.pdf-upload-container {
  width: 100%;
}

.pdf-uploader {
  width: 100%;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  line-height: 1.4;
}

:deep(.el-upload-list) {
  margin-top: 10px;
}

:deep(.el-upload-list__item) {
  transition: none;
}

:deep(.el-upload-list__item-name) {
  color: #606266;
}

:deep(.el-upload-list__item .el-icon-close) {
  color: #909399;
}

:deep(.el-upload-list__item .el-icon-close:hover) {
  color: #409eff;
}

.upload-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.file-input {
  width: 100%;
  margin-bottom: 10px;
}

.uploaded-file {
  margin-top: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.uploaded-file i {
  color: #909399;
}

.uploaded-image-container {
  margin-top: 10px;
  width: 178px;
  height: 178px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-box {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  padding: 30px 20px;
  text-align: center;
  transition: all 0.3s;
}

.upload-box:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.file-input {
  display: none;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

.uploaded-image-container {
  position: relative;
  margin-top: 15px;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.uploaded-image-container:hover .image-overlay {
  opacity: 1;
}

.image-overlay i {
  color: #fff;
  font-size: 24px;
  cursor: pointer;
}

.uploaded-file {
  margin-top: 15px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.delete-icon {
  margin-left: auto;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.delete-icon:hover {
  color: #f56c6c;
}

.selected-filename {
  margin-top: 8px;
  color: #409eff;
  font-size: 12px;
  word-break: break-all;
}

.nav {
  padding: 20px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-link {
  text-decoration: none;
  color: #909399;  /* 非当前页面使用灰色 */
  font-size: 16px;
  transition: color 0.3s;  /* 添加颜色过渡效果 */
}

.nav-link:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav span {
  color: #909399;  /* 分隔符使用灰色 */
  font-size: 16px;
  margin: 0 5px;
}

.current-page {
  color: #409EFF !important;  /* 当前页面使用蓝色 */
  font-weight: 500;  /* 当前页面加粗 */
}

.nav-back {
  position: absolute;
  right: 20px;
}

.nav-back .el-button {
  font-size: 14px;
  color: #909399;  /* 返回按钮使用灰色 */
}

.nav-back .el-button:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav-back i {
  margin-right: 5px;
}
</style>
